using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using BaseAmd.Mmp;
using BaseAmd.Mmp.FileNameFormat;
using BaseAmd.Ret;
using Newtonsoft.Json;
using Catastrophe.Common.FileM;
using Catastrophe.Common.Http;
using RestSharp;
using RestResponse = RestSharp.RestResponse;

namespace SiemensAmd.Mmp.Http.QT
{
	public class ProgHttpHandlerQt : IProgHandler
	{
		private string _httpServerIp = "localhost";

		private int _httpServerPort = 8016;

		public const int DefaultRequestTimeout = 10000;

		public Action<int, int, FileInfoEntity> DownLoadNcProcessHandler { get; set; }

		public Action<int, int> UploadPcProcessHandler { get; set; }

		public ProgHttpHandlerQt(ProgApiResources progApiRes)
		{
			HttpApiResources httpApiResources = (HttpApiResources)progApiRes;
			this._httpServerIp = httpApiResources.IpAdr;
		}

		public TransResult DeleteFile(List<string> fileAry, ProgApiResources apiRes)
		{
			TransResult transResult = new TransResult();
			BaseFileRename baseFileRename = this.FileRename();
			if (fileAry == null || fileAry.Count == 0)
			{
				transResult.IsSuccess = false;
				transResult.Message = "invalid param fileAry!";
				return transResult;
			}
			foreach (string item in fileAry)
			{
				string logicPath = baseFileRename.NameFormat(item, toUpper: true).LogicPath;
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(29, 3);
				defaultInterpolatedStringHandler.AppendLiteral("http://");
				defaultInterpolatedStringHandler.AppendFormatted(this._httpServerIp);
				defaultInterpolatedStringHandler.AppendLiteral(":");
				defaultInterpolatedStringHandler.AppendFormatted(this._httpServerPort);
				defaultInterpolatedStringHandler.AppendLiteral("/FileSvc/Remove?path=");
				defaultInterpolatedStringHandler.AppendFormatted(logicPath);
				string url = defaultInterpolatedStringHandler.ToStringAndClear();
				try
				{
					if (fileAry.Count > 0)
					{
						Thread.Sleep(200);
					}
					string value = HttpUtil.HttpGet(url, 5000);
					OperateAmdRet operateAmdRet = JsonConvert.DeserializeObject<OperateAmdRet>(value);
					if (!operateAmdRet.Success)
					{
						transResult.Message = operateAmdRet.Message;
						transResult.IsSuccess = false;
						return transResult;
					}
				}
				catch (Exception ex)
				{
					transResult.Message = ex.ToString();
					transResult.IsSuccess = false;
					return transResult;
				}
			}
			transResult.IsSuccess = true;
			return transResult;
		}

		public BaseFileRename FileRename()
		{
			return new BaseFileRename();
		}

		public Tuple<TransResult, List<FileInfoEntity>> GetProgDetails(string stationName, ProgApiResources apiRes)
		{
			try
			{
				TransResult transResult = new TransResult
				{
					IsSuccess = true
				};
				List<FileInfoEntity> list = new List<FileInfoEntity>();
				HttpApiResources httpApiResources = (HttpApiResources)apiRes;
				List<string> list2 = (from x in httpApiResources.RemotePath.Split('|')
					where x.Trim() != ""
					select x).ToList();
				if (list2.Count == 0)
				{
					transResult.Message = "path info error";
					transResult.IsSuccess = false;
					return new Tuple<TransResult, List<FileInfoEntity>>(transResult, list);
				}
				int num = 1;
				foreach (string item in list2)
				{
					if (list2.Count > 0)
					{
						Thread.Sleep(200);
					}
					DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(37, 3);
					defaultInterpolatedStringHandler.AppendLiteral("http://");
					defaultInterpolatedStringHandler.AppendFormatted(this._httpServerIp);
					defaultInterpolatedStringHandler.AppendLiteral(":");
					defaultInterpolatedStringHandler.AppendFormatted(this._httpServerPort);
					defaultInterpolatedStringHandler.AppendLiteral("/FileSvc/GetProgDetails?path=");
					defaultInterpolatedStringHandler.AppendFormatted(item);
					string url = defaultInterpolatedStringHandler.ToStringAndClear();
					RestResponse restResponse = HttpUtil.RequestBehaviorSync(url, Method.Get, "");
					if (!restResponse.IsSuccessful)
					{
						transResult.IsSuccess = false;
						transResult.Message = restResponse.ErrorMessage;
						return new Tuple<TransResult, List<FileInfoEntity>>(transResult, list);
					}
					GOperateAmdRet<List<ProgInfoQt>> gOperateAmdRet = JsonConvert.DeserializeObject<GOperateAmdRet<List<ProgInfoQt>>>(restResponse.Content);
					if (gOperateAmdRet.Success)
					{
						FileInfoEntity fileInfoEntity = new FileInfoEntity
						{
							QueryNodeId = 1 + list.Count,
							Name = item,
							FormatName = item,
							Path = item,
							FullName = item,
							IsDirectory = true,
							IsExist = true,
							IsValid = true,
							Type = FilePathTypeEnum.Dir,
							QueryParentNodeId = -1
						};
						num = fileInfoEntity.QueryNodeId;
						list.Add(fileInfoEntity);
						if (restResponse.Content == null)
						{
							continue;
						}
						for (int i = 0; i < gOperateAmdRet.Content.Count; i++)
						{
							ProgInfoQt progInfoQt = gOperateAmdRet.Content[i];
							if (!progInfoQt.IsDirectory)
							{
								FileInfo fileInfo = null;
								try
								{
									fileInfo = new FileInfo(progInfoQt.BaseName);
								}
								catch (Exception)
								{
									continue;
								}
								FileInfoEntity fileInfoEntity2 = new FileInfoEntity
								{
									QueryNodeId = i + 1 + list.Count,
									QueryParentNodeId = num,
									Name = progInfoQt.BaseName,
									FormatName = progInfoQt.BaseName,
									Path = item,
									FullName = progInfoQt.SrcPath,
									Extension = fileInfo.Extension,
									Size = progInfoQt.Size.ToString(),
									IsDirectory = progInfoQt.IsDirectory,
									ModifyTime = progInfoQt.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"),
									IsExist = true,
									IsValid = true,
									Type = (progInfoQt.IsDirectory ? FilePathTypeEnum.Dir : FilePathTypeEnum.File)
								};
								if (fileInfo.Extension != "")
								{
									fileInfoEntity2.NameWithoutExtension = fileInfoEntity2.Name.Replace(fileInfo.Extension, "");
								}
								if (fileInfoEntity2.Extension.StartsWith("."))
								{
									fileInfoEntity2.ExtensionWithoutPoint = fileInfoEntity2.Extension.Remove(0, 1);
								}
								list.Add(fileInfoEntity2);
							}
						}
						continue;
					}
					transResult.IsSuccess = false;
					transResult.Message = gOperateAmdRet.Message;
					break;
				}
				return new Tuple<TransResult, List<FileInfoEntity>>(transResult, list);
			}
			catch (Exception ex2)
			{
				return new Tuple<TransResult, List<FileInfoEntity>>(new TransResult
				{
					IsSuccess = false,
					Message = ex2.ToString()
				}, new List<FileInfoEntity>());
			}
		}

		public bool IsFileExist(string fileName, ProgApiResources apiRes)
		{
			Tuple<TransResult, List<FileInfoEntity>> progDetails = this.GetProgDetails("", apiRes);
			if (!progDetails.Item1.IsSuccess)
			{
				return false;
			}
			return progDetails.Item2.Any((FileInfoEntity x) => x.FullName == fileName);
		}

		public TransResult Rename(string srcName, string destName, string root, ProgApiResources apiRes)
		{
			throw new NotImplementedException();
		}

		public TransResult DownLoadNcSingle(FileInfoEntity srcFile, FileInfoEntity dstFileInfo, ProgApiResources apiRes)
		{
			return this.DownLoadNcMulti(new List<FileInfoEntity> { srcFile }, dstFileInfo.Path, apiRes);
		}

		public TransResult DownLoadNcMulti(List<FileInfoEntity> entityBuf, string remotePath, ProgApiResources apiRes)
		{
			try
			{
				HttpApiResources httpApiResources = (HttpApiResources)apiRes;
				TransResult transResult = new TransResult
				{
					IsSuccess = true
				};
				int count = entityBuf.Count;
				int num = 0;
				BaseFileRename baseFileRename = this.FileRename();
				foreach (FileInfoEntity item in entityBuf)
				{
					if (entityBuf.Count > 0)
					{
						Thread.Sleep(200);
					}
					string value;
					string value2;
					if (remotePath.ToUpper().StartsWith("//NC"))
					{
						value = "DownLoadNcSync";
						value2 = baseFileRename.NameFormat(Path.Combine(remotePath, item.Name), toUpper: true).RealPath;
					}
					else
					{
						value = "DownLoadPcSync";
						value2 = remotePath + item.Name.ToUpper();
					}
					DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(36, 4);
					defaultInterpolatedStringHandler.AppendLiteral("http://");
					defaultInterpolatedStringHandler.AppendFormatted(this._httpServerIp);
					defaultInterpolatedStringHandler.AppendLiteral(":");
					defaultInterpolatedStringHandler.AppendFormatted(this._httpServerPort);
					defaultInterpolatedStringHandler.AppendLiteral("/FileSvc/");
					defaultInterpolatedStringHandler.AppendFormatted(value);
					defaultInterpolatedStringHandler.AppendLiteral("?path=");
					defaultInterpolatedStringHandler.AppendFormatted(value2);
					defaultInterpolatedStringHandler.AppendLiteral("&timeout=3000");
					string url = defaultInterpolatedStringHandler.ToStringAndClear();
					string body = Encoding.GetEncoding("UTF-8").GetString(item.Content).Replace("\r\n", "\n");
					RestResponse restResponse = HttpUtil.RequestBehaviorSync(url, Method.Post, "text/plain", body);
					if (!restResponse.IsSuccessful)
					{
						transResult.IsSuccess = false;
						transResult.Message = restResponse.ErrorMessage;
						return transResult;
					}
					OperateAmdRet operateAmdRet = JsonConvert.DeserializeObject<OperateAmdRet>(restResponse.Content);
					if (!operateAmdRet.Success)
					{
						transResult.IsSuccess = false;
						transResult.Message = operateAmdRet.Message;
						return transResult;
					}
					num++;
					this.DownLoadNcProcessHandler?.BeginInvoke(count, num, item, null, null);
				}
				return transResult;
			}
			catch (Exception ex)
			{
				return new TransResult
				{
					Message = ex.ToString()
				};
			}
		}

		public TransResult UploadPcSingle(FileInfoEntity remoteFileInfo, string localPath, ProgApiResources apiRes)
		{
			if (!Directory.Exists(localPath))
			{
				return new TransResult
				{
					Message = localPath + " not exist"
				};
			}
			BaseFileRename baseFileRename = this.FileRename();
			string value;
			string value2;
			if (remoteFileInfo.Path.StartsWith("//NC"))
			{
				value = "UpLoadNcSync";
				value2 = baseFileRename.NameFormat(Path.Combine(remoteFileInfo.Path, remoteFileInfo.Name), toUpper: true).RealPath;
			}
			else
			{
				value = "UpLoadPcSync";
				value2 = remoteFileInfo.Path + remoteFileInfo.Name;
			}
			TransResult transResult = new TransResult
			{
				IsSuccess = true
			};
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(37, 4);
			defaultInterpolatedStringHandler.AppendLiteral("http://");
			defaultInterpolatedStringHandler.AppendFormatted(this._httpServerIp);
			defaultInterpolatedStringHandler.AppendLiteral(":");
			defaultInterpolatedStringHandler.AppendFormatted(this._httpServerPort);
			defaultInterpolatedStringHandler.AppendLiteral("/FileSvc/");
			defaultInterpolatedStringHandler.AppendFormatted(value);
			defaultInterpolatedStringHandler.AppendLiteral("?path=");
			defaultInterpolatedStringHandler.AppendFormatted(value2);
			defaultInterpolatedStringHandler.AppendLiteral("&timeout=30000");
			string url = defaultInterpolatedStringHandler.ToStringAndClear();
			try
			{
				RestResponse restResponse = HttpUtil.RequestBehaviorSync(url, Method.Get, "");
				if (!restResponse.IsSuccessful)
				{
					transResult.IsSuccess = false;
					transResult.Message = restResponse.ErrorMessage;
					return transResult;
				}
				GOperateAmdRet<string> gOperateAmdRet = JsonConvert.DeserializeObject<GOperateAmdRet<string>>(restResponse.Content);
				if (!gOperateAmdRet.Success)
				{
					transResult.IsSuccess = false;
					transResult.Message = gOperateAmdRet.Message;
					transResult.Content = gOperateAmdRet.Content;
					return transResult;
				}
				string path = Path.Combine(localPath, remoteFileInfo.Name);
				using (StreamWriter streamWriter = new StreamWriter(path))
				{
					streamWriter.Write(gOperateAmdRet.Content);
				}
				transResult.IsSuccess = true;
				return transResult;
			}
			catch (Exception ex)
			{
				transResult.IsSuccess = false;
				transResult.Message = ex.ToString();
				return transResult;
			}
		}

		private int GetTimeout(HttpApiResources res)
		{
			return (res.RequestTimeout > 0) ? res.RequestTimeout : 10000;
		}
	}
}
